package com.sunny.ihealth.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.sunny.ihealth.BaseActivity;
import com.sunny.ihealth.R;
import com.sunny.ihealth.data.BmobManager;
import com.sunny.ihealth.ui.view.SomeDialogs;
import com.sunny.ihealth.utils.PictureUtils;
import com.sunny.ihealth.utils.UriUtils;
import com.sunny.ninepictureview.NineAddPictureView;
import com.sunny.ninepictureview.PressGrayImageView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class PublishPostActivity extends BaseActivity implements View.OnClickListener, NineAddPictureView.genImageViewListener, NineAddPictureView.OnItemClickListener {

    public static final int REQUEST_CODE_CAMERA = 1;
    public static final int REQUEST_CODE_GALLERY = 2;

    //imageView的加载，错误图片
    private static final ColorDrawable gray = new ColorDrawable(Color.GRAY);
    private static final ColorDrawable darkGray = new ColorDrawable(Color.DKGRAY);

    private static final String TAG = "TAG::PublishPost";

    private EditText etContent;
    private Button btnPublish;
    private NineAddPictureView nineAddPictureView;
    private ProgressDialog progressDialog;

    //图片
    private File currentPhotoFile;
    private List<String> imgPaths;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_post);

        initViews();
        initData();
    }

    @Override
    public void initViews() {
        setEnableBackIcon(true);
        setStatusBarColor();
        setToolbar("分享");

        etContent = (EditText) findViewById(R.id.editText_publishPost_content);
        btnPublish = (Button) findViewById(R.id.btn_publishPost_publish);
        nineAddPictureView = (NineAddPictureView) findViewById(R.id.nineAddPictureView_publishPost_pics);
        progressDialog = SomeDialogs.unCancelableProgressDialog(this, "");

        btnPublish.setOnClickListener(this);
        nineAddPictureView.setGenImageViewListener(this);
        nineAddPictureView.setOnItemClickListener(this);
        nineAddPictureView.initState();
    }


    @Override
    public void initData() {
        imgPaths = new ArrayList<>();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_publishPost_publish:
                String content = etContent.getText().toString().trim();
                if (TextUtils.isEmpty(content) && imgPaths.size() == 0) {
                    Toast.makeText(PublishPostActivity.this, "先说点什么吧~", Toast.LENGTH_SHORT).show();
                    return;
                }

                btnPublish.setEnabled(false);
                nineAddPictureView.setEnabled(false);
                if (imgPaths.size() == 0) {
                    progressDialog.setMessage("正在发布...");
                    progressDialog.show();
                    publishPost(content);
                } else {
                    progressDialog.setMessage("正在上传照片...");
                    progressDialog.show();
                    publishPostWithPic(content, imgPaths);
                }
                break;
        }
    }


    //发表帖子
    private void publishPost(String content) {
        getBmob().publishPost(content, new BmobManager.Action1<Boolean>() {
            @Override
            public void onCompleted(Boolean aBoolean) {
                btnPublish.setEnabled(true);
                nineAddPictureView.setEnabled(true);
                progressDialog.dismiss();

                if (aBoolean != null && aBoolean) {
                    Toast.makeText(PublishPostActivity.this, "发送成功~", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    private void publishPostWithPic(String content, List<String> pics) {
        getBmob().publishPost(content, pics, new BmobManager.Action2<Boolean, Integer>() {
            @Override
            public void onCompleted(Boolean succeed, Integer progress) {
                if (progress < 0) {
                    Log.e(TAG, "发帖失败");
                } else if (!succeed && progress > 0) {
                    progressDialog.setMessage(String.format(Locale.getDefault(), "正在上传(%d/%d)", progress, imgPaths.size()));
                    return;
                } else if (succeed) {
                    Toast.makeText(PublishPostActivity.this, "发送成功~", Toast.LENGTH_SHORT).show();
                }

                btnPublish.setEnabled(true);
                nineAddPictureView.setEnabled(true);
                progressDialog.dismiss();
            }
        });
    }


    /**
     * 生成图片文件名
     *
     * @return
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");

        File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/");
        if (!file.exists()) {
            file.mkdirs();
        }
        return Environment.getExternalStorageDirectory() + "/DCIM/Camera/" + dateFormat.format(date) + ".jpg";
    }


    /**
     * 选择头像
     */
    private void choosePicture() {
        new AlertDialog.Builder(PublishPostActivity.this)
                .setTitle("选择图片")
                .setItems(new String[]{"拍照", "从相册中选择"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent;
                        if (which == 0) { //拍照
                            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            //调用前置摄像头
                            intent.putExtra("camerasensortype", 1);
                            currentPhotoFile = new File(getPhotoFileName());
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentPhotoFile));
                            startActivityForResult(intent, REQUEST_CODE_CAMERA);
                        } else {  //从相册选择
                            intent = new Intent(Intent.ACTION_PICK);
                            intent.setType("image/*");
                            startActivityForResult(intent, REQUEST_CODE_GALLERY);
                        }
                    }
                })
                .create()
                .show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择图片的uri
        Uri uri = null;
        if (requestCode == REQUEST_CODE_GALLERY && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                // 得到图片的全路径
                uri = data.getData();
            }
        } else if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            uri = PictureUtils.galleryAddPic(this, currentPhotoFile);
        }

        if (uri != null) {
            String path = UriUtils.getPath(this, uri);
            if (path == null) {
                Toast.makeText(PublishPostActivity.this, "图片添加失败...", Toast.LENGTH_SHORT).show();
                return;
            }

            String small = Environment.getExternalStorageDirectory() + "/small_" + new File(path).getName();
            if (PictureUtils.saveSmallBitmap(path, small, 720, 1280, 80)) {
                imgPaths.add(small);
                nineAddPictureView.addPicture(small);
            } else {
                Toast.makeText(PublishPostActivity.this, "图片压缩失败...", Toast.LENGTH_SHORT).show();
            }

        }

    }


    /**
     * 图片被按下
     *
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(View view, final int position) {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("您要移除该图片吗")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        nineAddPictureView.removePicture(position);
                        PictureUtils.deleteTempFile(imgPaths.get(position));
                        imgPaths.remove(position);
                    }
                })
                .create()
                .show();
    }

    /**
     * 添加按钮被按下
     */
    @Override
    public void onAddButtonClick() {
        choosePicture();
    }

    /**
     * 获取imgView
     *
     * @param path path为 ADD_BUTTON_PATH 时为创建添加按钮
     * @return
     */

    @Override
    public ImageView getImageView(String path) {
        System.out.println(path);
        if (NineAddPictureView.ADD_BUTTON_PATH.equals(path)) {
            ImageView iv = new ImageView(this);
            iv.setImageResource(R.drawable.bg_add_picture);
            return iv;
        } else {
            PressGrayImageView iv = new PressGrayImageView(this);
            Picasso
                    .with(this)
                    .load("file://" + path)
                    .resize(300, 300)
                    .centerCrop()
                    .placeholder(gray)
                    .error(darkGray)
                    .into(iv);
            return iv;
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (String path : imgPaths) {
            PictureUtils.deleteTempFile(path);
        }
    }
}
